# -*- coding: utf-8 -*-
import jieba
import re

def load_sentiment_dict(dict_path):
    """加载情感词典"""
    sentiment_dict = {}
    with open(dict_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#'):
                parts = line.split()
                if len(parts) >= 2:
                    word = parts[0]
                    score = int(parts[1])
                    sentiment_dict[word] = score
    return sentiment_dict

def preprocess_text(text):
    """预处理文本"""
    # 去除多余的空白字符
    text = re.sub(r'\s+', '', text)
    return text

def analyze_sentiment(text, sentiment_dict):
    """分析文本情感极性"""
    # 分词
    words = jieba.lcut(text)
    
    # 情感统计
    positive_score = 0
    negative_score = 0
    neutral_count = 0
    total_words = len(words)
    
    # 统计情感词
    positive_words = []
    negative_words = []
    
    for word in words:
        if word in sentiment_dict:
            score = sentiment_dict[word]
            if score > 0:
                positive_score += score
                positive_words.append((word, score))
            elif score < 0:
                negative_score += score
                negative_words.append((word, score))
        else:
            neutral_count += 1
    
    # 计算总体情感得分
    total_sentiment_score = positive_score + negative_score
    
    # 判断整体情感极性
    if total_sentiment_score > 0:
        overall_sentiment = "积极"
    elif total_sentiment_score < 0:
        overall_sentiment = "消极"
    else:
        overall_sentiment = "中性"
    
    return {
        'total_words': total_words,
        'positive_score': positive_score,
        'negative_score': negative_score,
        'total_sentiment_score': total_sentiment_score,
        'overall_sentiment': overall_sentiment,
        'positive_words': positive_words,
        'negative_words': negative_words,
        'neutral_count': neutral_count
    }

def main():
    # 加载情感词典
    print("正在加载情感词典...")
    sentiment_dict = load_sentiment_dict('sentiment_dict.txt')
    print(f"情感词典加载完成，共加载 {len(sentiment_dict)} 个情感词")
    
    # 读取红楼梦文本
    print("正在读取红楼梦文本...")
    with open('temp.txt', 'r', encoding='utf-8') as f:
        text = f.read()
    print(f"文本读取完成，共 {len(text)} 个字符")
    
    # 预处理文本
    text = preprocess_text(text)
    
    # 为节省时间，只分析前10000个字符
    text_to_analyze = text[:10000]
    print(f"开始分析前 {len(text_to_analyze)} 个字符的情感...")
    
    # 进行情感分析
    result = analyze_sentiment(text_to_analyze, sentiment_dict)
    
    # 输出结果
    print("\n" + "="*50)
    print("《红楼梦》文本情感分析结果")
    print("="*50)
    print(f"分析文本长度: {len(text_to_analyze)} 字符")
    print(f"总词数: {result['total_words']}")
    print(f"积极情感得分: {result['positive_score']}")
    print(f"消极情感得分: {result['negative_score']}")
    print(f"总体情感得分: {result['total_sentiment_score']}")
    print(f"整体情感极性: {result['overall_sentiment']}")
    print(f"中性词数量: {result['neutral_count']}")
    
    # 显示部分积极情感词
    print("\n部分积极情感词:")
    print("-" * 30)
    positive_sample = result['positive_words'][:10]
    for word, score in positive_sample:
        print(f"{word}: {score}")
    
    # 显示部分消极情感词
    print("\n部分消极情感词:")
    print("-" * 30)
    negative_sample = result['negative_words'][:10]
    for word, score in negative_sample:
        print(f"{word}: {score}")
    
    # 保存结果到文件
    with open('sentiment_analysis_result.txt', 'w', encoding='utf-8') as f:
        f.write("《红楼梦》文本情感分析结果\n")
        f.write("="*50 + "\n")
        f.write(f"分析文本长度: {len(text_to_analyze)} 字符\n")
        f.write(f"总词数: {result['total_words']}\n")
        f.write(f"积极情感得分: {result['positive_score']}\n")
        f.write(f"消极情感得分: {result['negative_score']}\n")
        f.write(f"总体情感得分: {result['total_sentiment_score']}\n")
        f.write(f"整体情感极性: {result['overall_sentiment']}\n")
        f.write(f"中性词数量: {result['neutral_count']}\n")
        
        f.write("\n部分积极情感词:\n")
        f.write("-" * 30 + "\n")
        for word, score in result['positive_words'][:20]:
            f.write(f"{word}: {score}\n")
            
        f.write("\n部分消极情感词:\n")
        f.write("-" * 30 + "\n")
        for word, score in result['negative_words'][:20]:
            f.write(f"{word}: {score}\n")
    
    print("\n情感分析结果已保存到 sentiment_analysis_result.txt 文件中")

if __name__ == "__main__":
    main()